package com.googlecode.androidspamblocker;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import android.content.Context;
import android.os.Bundle;
import android.telephony.SmsMessage;

public class SmsAddressFilter implements SmsFilter {
	private static final String TAG = "SmsAddressFilter";
	private static final String DELIMITER = ",";
	private Pattern pattern;
	private int action;
	private int hits = 0;
	private boolean enabled = true;
	
	public SmsAddressFilter() {
	}
	
	public SmsAddressFilter(String pattern, int action) throws PatternSyntaxException {
		this.pattern = Pattern.compile(pattern);
		this.action = action;
	}

	public String getPattern() {
		return pattern.pattern();
	}

	public void setPattern(String pattern) {
		this.pattern = Pattern.compile(pattern);
	}

	public int getAction() {
		return action;
	}

	public void setAction(int action) {
		this.action = action;
	}

	public boolean isEnabled() {
		return enabled;
	}

	public void setEnabled(boolean enabled) {
		this.enabled = enabled;
	}

	public int getHits() {
		return hits;
	}

	public int filter(SmsMessage message, Context context) {
		String address = message.getOriginatingAddress();
		Matcher matcher = pattern.matcher(address);
		if(enabled && matcher.find()) {
			hits++;
			return action;
		}
		return SmsAction.UNKNOWN;
	}
	
	public int filter(SmsMessage[] message, Context context) {
		return filter(message[0], context);
	}
	
	public void load(Bundle bundle) throws PatternSyntaxException {
		String str = bundle.getString("address");
		int act = bundle.getInt("action", SmsAction.UNKNOWN);
		pattern = Pattern.compile(str);
		action = act;
	}
	
	public void load(String filter) throws PatternSyntaxException, NumberFormatException {
		String[] fields = filter.split(DELIMITER);
		pattern = Pattern.compile(fields[0]);
		action = Integer.parseInt(fields[1]);
		hits = Integer.parseInt(fields[2]);
		enabled = Boolean.parseBoolean(fields[3]);
	}
	
	public String toString() {
		return pattern.pattern()
			+ DELIMITER + action
			+ DELIMITER + hits
			+ DELIMITER + enabled;
	}

}
